<template>
  <el-form ref="ruleFormRef" style="max-width: 80%" :model="data" :rules="rules" label-width="15%">
    <el-form-item label="年级：" prop="gradeLevel">
      <el-select v-model="data.gradeLevel" placeholder="年级" size="large" style="width: 240px;margin:0 10px;" filterable
        clearable>
        <el-option v-for="item in slevel" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="学科：" prop="subjectId">
      <el-select v-model="data.subjectId" placeholder="学科" size="large" style="width: 240px;margin:0 10px;" filterable
        clearable>
        <el-option v-for="item in subjectName" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="题干:" prop="title">
      <el-input v-model="data.title" style="width: 100%" size="large" @click="getinput('title')" />
    </el-form-item>
    <el-form-item label="选项:" prop="items">
      <div v-for="(item, i) in data.items" :key="item.predix"
        style="margin-top: 10px;display: flex; align-items: center;">
        <span style="flex: 0 0 10px; min-width: 10px;">{{ item.prefix }}</span>
        <el-input v-model="item.prefix" style="width: 10% ;margin: 0 15px;" size="large" />
        <el-input v-model="item.content" style="width: 70%" size="large" @click="getinput(`items[${i}].content`)" />
        <el-button type="danger" style="margin-left: 1rem;" @click="delitems(i)">
          <Delete style="width: 1em; height: 1em;color: white;" />
        </el-button>
      </div>
    </el-form-item>
    <el-form-item label="解析:" prop="analyze">
      <el-input v-model="data.analyze" style="width: 100%" size="large" @click="getinput('analyze')" />
    </el-form-item>
    <el-form-item label="分数:" prop="score">
      <el-input-number v-model="data.score" :min="0" :max="100" :precision="1" />
    </el-form-item>
    <el-form-item label="难度:" prop="difficult">
      <el-rate v-model="data.difficult" />
    </el-form-item>
    <el-form-item label="正确答案:" prop="correctArray">
      <el-checkbox-group v-model="data.correctArray">
        <el-checkbox v-for="item in data.items" :key="item.prefix" :value="item.prefix" :label="item.prefix" />
      </el-checkbox-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      <el-button type="success" @click="additems">添加选项</el-button>
      <el-button type="success" @click="look">预览</el-button>
    </el-form-item>
  </el-form>

  <el-dialog v-model="dialogVisible" width="50%" style="height: 400px;">
    <editor v-model="content" :init="editorConfig" api-key="cm0337kcvy808gl7x5jzc1caqx7pk3pyhrdpfkrf5sxk981g" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogVisible1" title="题目预览" width="500">
    <el-form :model="lookquest">
      <el-form-item v-html="lookquest.title"></el-form-item>
      <el-form-item>
        <span v-for="(item, index) in lookquest.items" :key="index" v-html="`${item.prefix}、${item.content}`"
          style="margin-right: 15px;"></span>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, watch, onMounted, onUnmounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useLocale, ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router';
import { subject, addquest, quest, search } from "@/api/paper"
import { Delete } from '@element-plus/icons-vue'
import Editor from '@tinymce/tinymce-vue'
const content = ref('')
const editorConfig = {
  height: 300,
  menubar: false,
  plugins: [
    'autolink', 'link', 'lists', 'charmap', 'preview',
    'searchreplace', 'visualblocks', 'fullscreen',
    'insertdatetime', 'table', 'code'
  ],
  toolbar: 'undo redo | blocks | bold italic | ' +
    'alignleft aligncenter alignright alignjustify | ' +
    'bullist numlist outdent indent | link table | removeformat | code | help',
}


const route = useRoute();
const router = useRouter()
const dialogVisible1=ref(false)
let lookquest = ref<any>({})
function look() {
  dialogVisible1.value = true
  lookquest.value = data.value
}
const id: any = route.query.id
const isInitializing = ref(false)
if (id) {
  search(id).then(res => {
    if (res.status === 200) {
      isInitializing.value = true // 开始初始化数据
      data.value = res.data.response
      isInitializing.value = false // 初始化数据完成
    }
  })
}
function delitems(i: any) {
  data.value.items.splice(i, 1)
}
function additems() {
  if (data.value.items.length === 0) {
    // 如果数组为空，从A开始
    data.value.items.push({
      prefix: "A",
      content: ""
    });
    return;
  }
  // 获取最后一个元素的prefix
  const lastItem = data.value.items[data.value.items.length - 1];
  const lastPrefix = lastItem.prefix;
  // 将prefix转换为大写字母
  const uppercasePrefix = lastPrefix.toUpperCase();
  // 检查是否为有效字母
  if (uppercasePrefix.length === 1 && /[A-Z]/.test(uppercasePrefix)) {
    // 获取字母的ASCII码
    const asciiCode = uppercasePrefix.charCodeAt(0);
    // 计算下一个字母的ASCII码 (A=65, B=66, ...)
    const nextAsciiCode = asciiCode + 1;
    // 转换为字母
    const nextPrefix = String.fromCharCode(nextAsciiCode);
    // 添加新项
    data.value.items.push({
      prefix: nextPrefix,
      content: ""
    });
  } else {
    // 如果最后一个prefix不是有效字母，默认从A开始
    data.value.items.push({
      prefix: "A",
      content: ""
    });
  }
}
const ruleFormRef = ref<FormInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      addquest(data.value).then(res => {
        if (res.status === 200) {
          ElMessage.success('编辑成功')
          setTimeout(() => {
            router.push('topic')
          }, 1500)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// 辅助函数：解析字段路径并设置值
const setNestedValue = (obj: any, path: string, value: string) => {
  try {
    // 分割路径为数组，处理如 items[0].content 这样的嵌套路径
    const keys = path.split('.').flatMap(key => {
      const match = key.match(/\[(\d+)\]/)
      if (match) {
        return [key.replace(/\[(\d+)\]/, ''), parseInt(match[1])]
      }
      return key
    })
    // 递归设置嵌套值
    let current = obj
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      // 如果是最后一个键，直接设置值
      if (i === keys.length - 1) {
        current[key] = value
        return true
      }
      // 如果当前键不存在，创建它
      if (current[key] === undefined) {
        // 如果下一个键是数字，创建数组
        if (typeof keys[i + 1] === 'number') {
          current[key] = []
        }
        // 否则创建对象
        else {
          current[key] = {}
        }
      }
      // 移动到下一层
      current = current[key]
    }
    return true
  } catch (error) {
    console.error('设置嵌套值失败', error)
    return false
  }
}

// 辅助函数：获取嵌套值
const getNestedValue = (obj: any, path: string): string => {
  try {
    // 分割路径为数组，处理如 items[0].content 这样的嵌套路径
    const keys = path.split('.').flatMap(key => {
      const match = key.match(/\[(\d+)\]/)
      if (match) {
        return [key.replace(/\[(\d+)\]/, ''), parseInt(match[1])]
      }
      return key
    })
    // 递归获取嵌套值
    let current = obj
    for (const key of keys) {
      if (current[key] === undefined) {
        return ''
      }
      current = current[key]
    }
    return current || ''
  } catch (error) {
    console.error('获取嵌套值失败', error)
    return ''
  }
}
const dialogVisible = ref(false)
let inp = ''
function getinput(n: string) {
  inp = n
  content.value = getNestedValue(data.value, n) || ''
  dialogVisible.value = true
}
function save() {
  if (inp && content.value) {
    content.value = content.value.replace(/<[^>]+>/g, '');
    setNestedValue(data.value, inp, content.value)
    dialogVisible.value = false;
  }
}
let data = ref<any>({
  analyze: "",
  correct: '',
  correctArray: [],
  difficult: "",
  gradeLevel: "",
  id: "",
  itemOrder: '',
  items: [
    { prefix: "A", content: "" },
    { prefix: "B", content: "" },
    { prefix: "C", content: "" },
    { prefix: "D", content: "" }],
  questionType: 2,
  score: "",
  subjectId: '',
  title: "",
})
const sub = ref<{ id: number, label: string, level: number }[]>([])
subject().then(res => {
  const subject = res.data.response.map((subject: any) => {
    const subjectName = subject ? `${subject.name}(${subject.levelName})` : '未知学科'
    return { id: subject.id, label: subjectName, level: subject.level }
  })
  sub.value = subject
})
let subjectName = computed<{ id: number; label: string; level: number; }[]>(() => {
  if (!data.value.gradeLevel) return []
  const selectedLevel = data.value.gradeLevel
  return sub.value.filter(subject => subject.level === selectedLevel)
})
watch(() => data.value.gradeLevel, () => {
  if (isInitializing.value) {
    data.value.subjectId = ''
  }
})

const slevel = ref([
  { label: '一年级', value: 1 },
  { label: '二年级', value: 2 },
  { label: '三年级', value: 3 },
  { label: '四年级', value: 4 },
  { label: '五年级', value: 5 },
  { label: '六年级', value: 6 },
  { label: '初一', value: 7 },
  { label: '初二', value: 8 },
  { label: '初三', value: 9 },
  { label: '高一', value: 10 },
  { label: '高二', value: 11 },
  { label: '高三', value: 12 },
])

const rules = reactive<FormRules>({
  gradeLevel: [{ required: true, message: '请选择年级', trigger: 'blur' },],
  subjectId: [{ required: true, message: '请选择学科', trigger: 'blur', },],
  items: [{ required: true, message: '请选输入选项', trigger: 'blur', },],
  analyze: [{ required: true, message: '请输入解析', trigger: 'blur' },],
  title: [{ required: true, message: '请输入题干', trigger: 'blur' },],
  score: [{ required: true, message: '请输入分值', trigger: 'blur' },],
  difficult: [{ required: true, message: '请选择难度', trigger: 'blur' },],
  correctArray: [{ required: true, message: '请选择答案', trigger: 'blur' },],
})

</script>

<style scoped></style>